<?php
set_time_limit(0);
/***************************************************************
*  Copyright notice
*
*  (c) 2012  <>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 * Hint: use extdeveval to insert/update function index above.
 */

require_once(PATH_tslib.'class.tslib_pibase.php');


/**
 * Plugin 'Kategory ADD' for the 'mtkatalogi_add' extension.
 *
 * @author	 <>
 * @package	TYPO3
 * @subpackage	tx_mtkatalogiadd
 */
class tx_mtkatalogiadd_pi1 extends tslib_pibase {
	var $prefixId      = 'tx_mtkatalogiadd_pi1';		// Same as class name
	var $scriptRelPath = 'pi1/class.tx_mtkatalogiadd_pi1.php';	// Path to this script relative to the extension dir.
	var $extKey        = 'mtkatalogi_add';	// The extension key.
	var $pi_checkCHash = true;
	
	/**
	 * The main method of the PlugIn
	 *
	 * @param	string		$content: The PlugIn content
	 * @param	array		$conf: The PlugIn configuration
	 * @return	The content that is displayed on the website
	 */
	function main($content, $conf) {
		$this->conf = $conf;
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();

		//$content=$this->addkatlist();
		//$content=$this->show_script_menu();
		$content=$this->create_category();
		
		return $this->pi_wrapInBaseClass($content);
	}
	function create_category()
	{
			$where = 'deleted=0 AND sitemap!="brak" AND pid='.$this->conf['pid'].'';
			$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,www,mapacontent,skrypt','tx_mtkatalogiadd_www',$where,'','',10);	
			while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
			{
				$addquery=array('hidden'=>0);
				$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_mtkatalogiadd_www', 'uid='.$row['uid'],$addquery);		
				$setres = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);						
			
				$parse=$this->mapacontent($row['mapacontent'],$row['www'],$row['skrypt'],$row['uid']);
			}
			
			return '
			<script type="text/javascript">
			
			setTimeout("window.parent.location=\'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].'\'",3000);
			
			</script>
			';
			
	}
	function mapacontent($mapacontent,$www,$skrypt,$www_uid)
	{
		$mapacontent=str_replace('\"','"',$mapacontent);
		preg_match_all('/href=[\"\']?([^\"\'>]*)[\"\']?[^>]*>(.*?)<\/a>/si',$mapacontent,$out,PREG_SET_ORDER);
		
		for($i=0; $i<count($out); $i++)
		{
			$text=strip_tags($out[$i][2]);
			$link=$out[$i][1];
			//print_r($text."\n");
			if(strlen($text)>3 && strlen($text)<40 && intval($text)==0 && strlen($link)>1 && stristr($link,$www))
			{
				$dont=0;
				$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['pid'].' AND title="'.addslashes($text).'" AND script='.$skrypt;
				
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,www','tx_mtkatalogiadd_category',$where,'','',1);	
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$dont=1;
					
					$getwww=explode(',',$row['www']);
					if(!in_array($www_uid,$getwww) && $www_uid!=$row['www'])
					{
						$addquery=array('www'=>$row['www'].','.$www_uid);
						$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_mtkatalogiadd_category', 'uid='.$row['uid'],$addquery);		
						$setres = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
						
						unset($addcat);
						
						$addcat=array(
							'pid'		=>	$this->conf['catlink_pid'],
							'www'		=>	$www_uid,
							'category'	=>	$row['uid'],
							'link'		=>	$link
							
						);
						$addcat['crdate']=$addcat['tstamp']=time();
						$GLOBALS['TYPO3_DB']->exec_INSERTquery(
							'tx_mtkatalogiadd_catlink',
							$addcat   			
						);
						
					}
				}	
				if($dont==0)
				{
					$addcat=array(
						'pid'		=>	$this->conf['pid'],
						'title'		=>	$text,
						'script'	=>	$skrypt,
						'www'		=>	$www_uid
					);
					$addcat['crdate']=$addcat['tstamp']=time();
					$GLOBALS['TYPO3_DB']->exec_INSERTquery(
						'tx_mtkatalogiadd_category',
						$addcat   			
					);
					$uid_category=$GLOBALS['TYPO3_DB']->sql_insert_id();
					unset($addcat);
					
					$addcat=array(
						'pid'		=>	$this->conf['catlink_pid'],
						'www'		=>	$www_uid,
						'category'	=>	$uid_category,
						'link'		=>	$link
						
					);
					$addcat['crdate']=$addcat['tstamp']=time();
					$GLOBALS['TYPO3_DB']->exec_INSERTquery(
						'tx_mtkatalogiadd_catlink',
						$addcat   			
					);
					
				}
			}
		}	
	}
	function show_script_menu()
	{
		

		if(!isset($this->piVars['parse_www']) && !isset($this->piVars['script']))
		{
			return $this->get_script('parse_www');
		}else
		{
			$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['pid'].' AND uid NOT IN(1) AND skrypt='.intval($this->piVars['script']);
			$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,www','tx_mtkatalogiadd_www',$where,'','',1);	
			while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
			{
				//print_r($row['www']."\n");
				$get=$this->get($row['www']);
				//print_r(strlen($get).',');

				
				//preg_match_all('/<a.*href=[\"\']?([^\"\'>]*)[\"\']?[^>]*>(.*)<\/a>/si',$get,$out,PREG_SET_ORDER);
				preg_match_all('/href=[\"\']?([^\"\'>]*)[\"\']?[^>]*>(.*?)<\/a>/si',$get,$out,PREG_SET_ORDER);
				//print_r($out);
				
				$isset=0;
				if(1==1)
				{
					for($i=0; $i<count($out); $i++)
					{
						$link=$out[$i];
						if(stristr(strtolower($link[2]),'mapa') && stristr(strtolower($link[2]),'kata') || stristr(strtolower($link[2]),'mapa') && stristr(strtolower($link[2]),'stron'))
						{
							if(strlen($link[2])<100 && $isset==0)
							{
								$maplink=$link[1];
								$getmapa=$this->get($link[1]);
								
								$addquery=array(
								'sitemap'	=>	$maplink,
								'hidden'	=>	1,
								'mapacontent'	=> addslashes($getmapa)	
								);

								$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_mtkatalogiadd_www', 'uid='.$row['uid'],$addquery);		
								$setres = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
								$isset=1;
								break;
								
								/*
								preg_match_all('/href=[\"\']?([^\"\'>]*)[\"\']?[^>]*>(.*?)<\/a>/si',$get,$out,PREG_SET_ORDER);
							//	print_r($out); exit;
								foreach($out as $cat)
								{
									if(stristr($cat[1],$row['www']) && strip_tags($cat[2])!='' && strlen(strip_tags($cat[2]))>3 &&  strlen(strip_tags($cat[2]))<20)
									{
										//$add[]=$this->get_www_category($cat[1],$cat[2],$row['uid'],intval($this->piVars['script']));
										// get_www_category($link,$name,$webuid,$script)
										
										$add_link[]=$cat[1];
										$add_name[]=strip_tags(trim($cat[2]));
										$add_script[]=intval($this->piVars['script']);
										$isset=1;
									}
								}
								*/								
							}
							
						}
					}
					
					if($isset==0)
					{
						$addquery=array('sitemap'	=>	'brak','hidden'=>1);
						$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_mtkatalogiadd_www', 'uid='.$row['uid'],$addquery);		
						$setres = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
						$isset=1;
						break;
					}
					/*
					else
					{
						//$add=$this->get_www_category($add_link,$add_name,$row['uid'],intval($this->piVars['script']));
						//print_r($add);exit;
						//$addquery=array('allcategory'=>implode(',',$add),'sitemap'	=>	$maplink,'hidden'=>1);
						$addquery=array(
						'sitemap'	=>	$maplink,
						'hidden'=>1
						);
						$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_mtkatalogiadd_www', 'uid='.$row['uid'],$addquery);		
						$setres = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
						$isset=1;
						break;
					}
					*/
				}
				

			}
			
			return '
			<script type="text/javascript">
			
			setTimeout("window.parent.location=\'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].'\'",10000);
			
			</script>
			';
			
		}
	}
	function get_www_category($link,$name,$webuid,$script)
	{
		$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['pid'].' AND title=IN('.implode(',',$name).') AND script='.$script;
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('title','tx_mtkatalogiadd_category',$where,'','',1);	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{
			$title[]=$row['title'];
		}
		
		for($i=0; $i<count($name); $i++)
		{
			if(!in_array($name[$i],$title))
			{
				$addcat=array(
					'pid'		=>	$this->conf['pid'],
					'title'		=>	$name[$i],
					'script'	=>	$script
				);
				$addcat['crdate']=$addcat['tstamp']=time();
				$GLOBALS['TYPO3_DB']->exec_INSERTquery(
					'tx_mtkatalogiadd_category',
					$addcat   			
				);
				$uid[]=$GLOBALS['TYPO3_DB']->sql_insert_id();
			}
		}
		
		$linkuid=0;
		$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['catlink_pid'].' AND www='.$webuid.' AND link= IN('.implode(',',$link).')';
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('link','tx_mtkatalogiadd_catlink',$where);	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{
			$linkuid[]=$row['link'];
		}
		for($i=0; $i<count($linkuid); $i++)
		{
			if(!in_array($linkuid[$i],$link))
			{
				$addcat=array(
					'pid'		=>	$this->conf['catlink_pid'],
					'www'		=>	$webuid,
					'category'	=>	$uid,
					'link'		=>	$link[$i]
					
				);
				$addcat['crdate']=$addcat['tstamp']=time();
				$GLOBALS['TYPO3_DB']->exec_INSERTquery(
					'tx_mtkatalogiadd_catlink',
					$addcat   			
				);
			}		
		}
		if($linkuid==0)
		{

		}
		return $uid;
		
	}
	function addkatlist()
	{
		if(!isset($this->piVars['list']) && !isset($this->piVars['add']))
		{
			return $this->form('add_list');
		}
		elseif(isset($this->piVars['skrypt']))
		{
			$link=$this->piVars['list'];

			$get=$this->get($link);
			preg_match_all('#<td bgcolor=[^>]*>(.*)</td>#isU',$get,$return,PREG_SET_ORDER);
			preg_match_all('/href=[\"\']?([^\"\'>]*)[\"\']?[^>]*>(.*?)<\/a>/si',$return[0][1],$out,PREG_SET_ORDER);
			$number=$out[count($out)-2][2];

			if(stristr($link,',0.html'))
			{
				list($link)=explode(',0.html',$link);
				//print_r($link);exit;
			}

			for($i=0; $i<$number; $i++)
			{
				if($i==0) $this->addwww($link.',0.html');
				else $this->addwww($link.','.($i*50).'.html');
			}
			
		}
	}
	
	function addwww($link)
	{
		$get=$this->get($link);
		preg_match_all('#<tr[^>]*>(.*)</tr>#isU',$get,$return,PREG_SET_ORDER);
		print_r($link."\n");
		for($i=0; $i<count($return); $i++)
		{
			$txt=$return[$i][1];
			preg_match_all('/href=[\"\']?([^\"\'>]*)[\"\']?[^>]*>(.*?)<\/a>/si',$txt,$out,PREG_SET_ORDER);
			//print_r($out);exit;
			if(count($out)==3)
			{	
				$add[$i]=array(
					'www'	=>	$out[0][1],
					'title'	=>	$out[0][2],
					'skrypt'	=>	intval($this->piVars['skrypt'])
				);	
			}
			if(count($out)==4)
			{
				$add[$i]=array(
					'www'		=>	$out[0][1],
					'title'		=>	$out[0][2],
					'kategoria'	=>	$this->get_category($out[1][2]),
					'skrypt'	=>	intval($this->piVars['skrypt'])
				);	
			}
			
		
			preg_match_all('#<a class=\"porcjowanie\" rel=\"pr\"[^>]*><B>(.*)</B></a>#isU',$txt,$pr,PREG_SET_ORDER);
			preg_match_all('#<a class=\"porcjowanie\" rel=\"ip\"[^>]*><b>(.*)</b></a>#isU',$txt,$ip,PREG_SET_ORDER);
			preg_match_all('#<td align=\"center\" class=\"szczegoly\" width=\"20%\"[^>]*>(.*)</td>#isU',$txt,$info,PREG_SET_ORDER);

			preg_match_all('#<td align=\"center\"[^>]*>(.*)</td>#isU',$txt,$td,PREG_SET_ORDER);
			
			$add[$i]['descinfo']=strip_tags($info[0][1]);
			
			for($z=0; $z<count($pr); $z++)
			{
				if($pr[0][1]!='') $add[$i]['pr']=$pr[0][1];
			}
			for($z=0; $z<count($ip); $z++)
			{
				if($ip[0][1]!='') $add[$i]['ip']=$ip[0][1];
			}
			if(count($td)==5)
			{
					if(strip_tags($td[2][1]=='N')) $add[$i]['linkreturn']=0;
					else $add[$i]['linkreturn']=1;
					
					$rest=explode('/',str_replace(' ','',strip_tags($td[3][1])));
					print_r($rest);
					$add[$i]['seo']=$rest[0]=='N'?0:1;
					$add[$i]['free']=$rest[1]=='N'?0:1;
					$add[$i]['moderowany']=$rest[2]=='N'?0:1;
					
				
			}

			if($add[$i]['www']!='')
			{
				$uid=0;
				$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['pid'].' AND www="'.mysql_real_escape_string($add[$i]['www']).'"';
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tx_mtkatalogiadd_www',$where);	
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$uid=$row['uid'];	
				}
				if($uid==0)
				{
					$add[$i]['pid']=$this->conf['pid'];
					$add[$i]['crdate']=$add[$i]['tstamp']=time();
					
					
					$GLOBALS['TYPO3_DB']->exec_INSERTquery(
						'tx_mtkatalogiadd_www',
						$add[$i]    			
					);
					
					
					//print_r($add[$i]);
				}
			}
		}			
	}
	function get_category($name)
	{
		$uid='';
		$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['cat_pid'].' AND title="'.mysql_real_escape_string($name).'"';
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tt_news_cat',$where);	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{	
			$uid=$row['uid'];
		}
		if($uid=='')
		{
			$addquery=array(
				'pid'		=>	$this->conf['cat_pid'],
				'title'		=>	mysql_real_escape_string($name),
				'tstamp'	=>	time(),
				'crdate'	=>	time()
			);
			$GLOBALS['TYPO3_DB']->exec_INSERTquery(
				'tt_news_cat',
				$addquery    			
			);
			$uid=$GLOBALS['TYPO3_DB']->sql_insert_id();
		}
		return $uid;
	}
	function form($opt)
	{
		switch($opt)
		{
			case 'add_list':
				return '
					<form action="" method="post">
						<textarea name="'.$this->prefixId.'[list]" cols="75" rows="5"></textarea><br />
						'.$this->get_script('list').'<br />
						<input name="'.$this->prefixId.'[add]" type="submit" />
						
					</form>
				';
			break;
		}
	}
	function get_script($opt='')
	{
		$where = 'deleted=0 AND hidden=0 AND pid='.$this->conf['pid'];
		$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','tx_mtkatalogiadd_skrypt',$where);	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
		{	
			$add[]=$row;
		}
		if($opt!='')
		{
			switch($opt)
			{
				case 'list':
				
					for($i=0; $i<count($add); $i++)
					{
						$return[]='<option value="'.$add[$i]['uid'].'">'.$add[$i]['title'].'</option>';
					}
					return '<select name="'.$this->prefixId.'[skrypt]">'.implode("\n",$return).'</select>';
				break;
				case 'parse_www':
					for($i=0; $i<count($add); $i++)
					{
						$array_param = array(
						'useCacheHash' => 0,
						'parameter' => $GLOBALS["TSFE"]->page['uid'].' _self',
						'additionalParams' => '&'.$this->prefixId.'[script]='.$add[$i]['uid'].'&'.$this->prefixId.'[parse_www]=1',
						
						);							
						$return[]='<li>'.$this->cObj->typolink($add[$i]['title'],$array_param).'</li>';
						return '<ul>'.implode("\n",$return).'</ul>';
					}
				break;
			}
		}else return $add;
		
	}
	function get($url) 
	{
		$process = curl_init($url);
		curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
		curl_setopt($process, CURLOPT_HEADER, 0);
		curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
		if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
		if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
		curl_setopt($process,CURLOPT_ENCODING , $this->compression);
		curl_setopt($process, CURLOPT_TIMEOUT, 30);
		if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
		curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
		$return = curl_exec($process);
		curl_close($process);
		return $return; 
	} 
}



if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mtkatalogi_add/pi1/class.tx_mtkatalogiadd_pi1.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mtkatalogi_add/pi1/class.tx_mtkatalogiadd_pi1.php']);
}

?>